import { extend } from 'umi-request';
import { SERVER_SCOPE } from './constants';

interface MindModel {
    value: string | null;
    text: string;
    isDefault: boolean | null;
}

const prefix = `${SERVER_SCOPE}/api`

const request = extend({
    prefix,
    timeout: 60000
});

/**
 * 收藏文章
 */
export const collectUrl = async (params: { url: string, title: string, userGuid: string, accessToken: string, content?: string
    ,num?: number
 }) => {
    const { url, title, userGuid, accessToken, content,num } = params
    
    console.log('调用 collectUrl API - Calling collectUrl API with params:', {
        url,
        title,
        userGuid,
        contentLength: content?.length || 0,
        num
    });

    try {
        console.log('发送请求到 /Crawler/GetUrl - Sending request to /Crawler/GetUrl');
        console.log('API 请求地址 - API request URL:', `${prefix}/Crawler/GetUrl`);
        
        const response = await request.post('/Crawler/GetUrl', {
            headers: {
                Authorization: `Bearer ${accessToken}`
            },
            data: {
                url,
                title,
                userGuid,
                content,
                num
            },
        });
        
        console.log('收藏 API 响应 - Collection API response:', response);
        return response;
    } catch (error) {
        console.error('收藏 API 错误 - Collection API error:', error);
        // 打印详细错误信息
        if (error.response) {
            console.error('错误响应数据 - Error response data:', error.response.data);
            console.error('错误响应状态 - Error response status:', error.response.status);
        } else if (error.request) {
            console.error('请求已发送但无响应 - Request was made but no response received');
        }
        
        return { isSuccess: false, message: error.message || 'Collection failed' };
    }
}

/**
 * 加载用户思维模型选项
 */
export const loadUserMindOptions = async (params: { userGuid: string, accessToken: string }) => {
    const { userGuid, accessToken } = params;

    try {
        console.log('发送请求到 /AgentPrompt/LoadUserMindOptions - Sending request to /AgentPrompt/LoadUserMindOptions');
        console.log('API 请求地址 - API request URL:', `${prefix}/AgentPrompt/LoadUserMindOptions`);
        
        // 打印完整的请求参数
        console.log('请求参数 - Request parameters:', {
            userGuid,
            accessToken: accessToken ? '已设置/Set' : '未设置/Not set'
        });
        
        // 对照GetUrl API的调用方式
        const response = await request.post('/AgentPrompt/LoadUserMindOptions', {
            headers: {
                Authorization: `Bearer ${accessToken}`
            },
            data: {
                userGuid
            }
        });
        
        // 详细记录响应内容
        console.log('LoadUserMindOptions API 响应 - Response:', response);
        console.log('响应是否成功 - Response success:', response.isSuccess);
        console.log('响应数据 - Response data:', response.data);
        console.log('响应数据类型 - Response data type:', typeof response.data);
        console.log('响应数据长度 - Response data length:', Array.isArray(response.data) ? response.data.length : 'not an array');

        return response;
    } catch (error) {
        console.error('加载用户思维模型选项失败 - Failed to load user mind options:', error);
        // 打印详细错误信息
        if (error.response) {
            console.error('错误响应数据 - Error response data:', error.response.data);
            console.error('错误响应状态 - Error response status:', error.response.status);
        } else if (error.request) {
            console.error('请求已发送但无响应 - Request was made but no response received');
        }
        return { isSuccess: false, message: error.message || 'Failed to load user mind options', data: [] };
    }
}

/**
 * 加载信息标签选项（分类）
 */
export const loadInfoTagOptions = async (params: { userGuid: string, accessToken: string }) => {
    const { userGuid, accessToken } = params;

    try {
        console.log('发送请求到 /Info/LoadInfoTagOptions - Sending request to /Info/LoadInfoTagOptions');
        console.log('API 请求地址 - API request URL:', `${prefix}/Info/LoadInfoTagOptions`);
        
        // 打印完整的请求参数
        console.log('请求参数 - Request parameters:', {
            userGuid,
            accessToken: accessToken ? '已设置/Set' : '未设置/Not set'
        });
        
        // 参考LoadUserMindOptions的调用方式
        const response = await request.post('/Info/LoadInfoTagOptions', {
            headers: {
                Authorization: `Bearer ${accessToken}`
            },
            data: {
                userGuid
            }
        });
        
        // 详细记录响应内容
        console.log('LoadInfoTagOptions API 响应 - Response:', response);
        console.log('响应是否成功 - Response success:', response.isSuccess);
        console.log('响应数据 - Response data:', response.data);
        console.log('响应数据类型 - Response data type:', typeof response.data);
        console.log('响应数据长度 - Response data length:', Array.isArray(response.data) ? response.data.length : 'not an array');

        return response;
    } catch (error) {
        console.error('加载信息标签选项失败 - Failed to load info tag options:', error);
        // 打印详细错误信息
        if (error.response) {
            console.error('错误响应数据 - Error response data:', error.response.data);
            console.error('错误响应状态 - Error response status:', error.response.status);
        } else if (error.request) {
            console.error('请求已发送但无响应 - Request was made but no response received');
        }
        return { isSuccess: false, message: error.message || 'Failed to load info tag options', data: [] };
    }
}

/**
 * 加载系统思维模型选项
 */
export const loadSystemMindOptions = async (params: { userGuid: string, accessToken: string }) => {
    const { userGuid, accessToken } = params;

    try {
        console.log('发送请求到 /AgentPrompt/LoadSystemMindOptions - Sending request to /AgentPrompt/LoadSystemMindOptions');
        console.log('API 请求地址 - API request URL:', `${prefix}/AgentPrompt/LoadSystemMindOptions`);
        
        // 打印完整的请求参数
        console.log('请求参数 - Request parameters:', {
            userGuid,
            accessToken: accessToken ? '已设置/Set' : '未设置/Not set'
        });
        
        // 参考loadUserMindOptions的调用方式
        const response = await request.post('/AgentPrompt/LoadSystemMindOptions', {
            headers: {
                Authorization: `Bearer ${accessToken}`
            },
            data: {
                userGuid // 添加 userGuid，与用户思维模型保持一致
            }
        });
        
        // 详细记录响应内容
        console.log('LoadSystemMindOptions API 响应 - Response:', response);
        console.log('响应是否成功 - Response success:', response.isSuccess);
        console.log('响应数据 - Response data:', response.data);
        console.log('响应数据类型 - Response data type:', typeof response.data);
        console.log('响应数据长度 - Response data length:', Array.isArray(response.data) ? response.data.length : 'not an array');

        return response;
    } catch (error) {
        console.error('加载系统思维模型选项失败 - Failed to load system mind options:', error);
        // 打印详细错误信息
        if (error.response) {
            console.error('错误响应数据 - Error response data:', error.response.data);
            console.error('错误响应状态 - Error response status:', error.response.status);
        } else if (error.request) {
            console.error('请求已发送但无响应 - Request was made but no response received');
        }
        return { isSuccess: false, message: error.message || 'Failed to load system mind options', data: [] };
    }
}

/**
 * 生成AI内容
 */
export const fetchGenerateAIContent = async (params: { 
    userGuid: string, 
    infoGuid: string, 
    mindPromptGuids: string[],
    accessToken: string 
}) => {
    const { userGuid, infoGuid, mindPromptGuids, accessToken } = params;

    try {
        const response = await request.post('/AgentPrompt/GenAIMindsExtend', {
            headers: {
                Authorization: `Bearer ${accessToken}`
            },
            data: {
                userGuid,
                infoGuid,
                mindPromptGuids
            },
        });

        return response;
    } catch (error) {
        console.log(error);
        return { 
            isSuccess: false, 
            message: error.message || 'Failed to generate AI content',
            data: '**Error generating content**\n\nThere was an error processing your request. Please try again later.'
        };
    }
}

/**
 * 关联标签（分类）
 */
export const relateTag = async (params: { infoGuid: string, tagName: string, userGuid: string, accessToken: string }) => {
    const { infoGuid, tagName, userGuid, accessToken } = params;

    try {
        console.log('发送请求到 /Info/RelateTag - Sending request to /Info/RelateTag');
        console.log('API 请求地址 - API request URL:', `${prefix}/Info/RelateTag`);
        
        // 打印完整的请求参数
        console.log('请求参数 - Request parameters:', {
            infoGuid,
            tagName,
            userGuid,
            accessToken: accessToken ? '已设置/Set' : '未设置/Not set'
        });
        
        const response = await request.post('/Info/RelateTag', {
            headers: {
                Authorization: `Bearer ${accessToken}`
            },
            data: {
                infoGuid,
                tagName
            }
        });
        
        // 详细记录响应内容
        console.log('RelateTag API 响应 - Response:', response);
        console.log('响应是否成功 - Response success:', response.isSuccess);
        console.log('响应数据 - Response data:', response.data);
        console.log('响应消息 - Response message:', response.message);

        return response;
    } catch (error) {
        console.error('关联标签失败 - Failed to relate tag:', error);
        // 打印详细错误信息
        if (error.response) {
            console.error('错误响应数据 - Error response data:', error.response.data);
            console.error('错误响应状态 - Error response status:', error.response.status);
        } else if (error.request) {
            console.error('请求已发送但无响应 - Request was made but no response received');
        }
        return { isSuccess: false, message: error.message || 'Failed to relate tag', data: null };
    }
}